<template>
  <div class="exam-detail-page">
    <van-nav-bar title="考试详情" left-arrow @click-left="onClickLeft" />

    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <template v-else-if="examDetail">
      <div class="content-container">
        <!-- 考试信息卡片 -->
        <div class="exam-card">
          <div class="exam-title">{{ examDetail.exam_name }}</div>
          <div class="exam-status-tag" :class="getStatusClass()">
            {{ getStatusText() }}
          </div>

          <div class="exam-info">
            <div class="info-item">
              <van-icon name="clock-o" />
              <span>考试时间:</span>
              <span>{{
                formatTimeRange(examDetail.start_time, examDetail.end_time)
              }}</span>
            </div>
            <div class="info-item">
              <van-icon name="underway-o" />
              <span>考试时长:</span>
              <span>{{ examDetail.paper?.duration || 0 }}分钟</span>
            </div>
            <div class="info-item">
              <van-icon name="todo-list-o" />
              <span>试卷名称:</span>
              <span>{{ examDetail.paper?.paper_name || "未知" }}</span>
            </div>
            <div class="info-item">
              <van-icon name="question-o" />
              <span>题目数量:</span>
              <span>{{ examDetail.paper?.question_list?.length || 0 }}题</span>
            </div>
            <div class="info-item">
              <van-icon name="gem-o" />
              <span>总分值:</span>
              <span>{{ examDetail.paper?.total_score || 0 }}分</span>
            </div>
            <div class="info-item" v-if="examDetail.description">
              <van-icon name="description" />
              <span>考试说明:</span>
              <span>{{ examDetail.description }}</span>
            </div>
          </div>
        </div>

        <!-- 考试须知 -->
        <div class="notice-card">
          <div class="card-title">考试须知</div>
          <div class="notice-item">
            <div class="notice-dot"></div>
            <div>
              考试时间: {{ examDetail.paper?.duration }}分钟，开始后计时不可暂停
            </div>
          </div>
          <div class="notice-item">
            <div class="notice-dot"></div>
            <div>
              题目数量:
              {{
                examDetail.paper?.question_list?.length
              }}道，请合理安排答题时间
            </div>
          </div>
          <div class="notice-item">
            <div class="notice-dot"></div>
            <div>提交后将立即结束考试，无法重新作答</div>
          </div>
          <div class="notice-item">
            <div class="notice-dot"></div>
            <div>系统会自动保存答案，避免意外丢失</div>
          </div>
          <div class="notice-item">
            <div class="notice-dot"></div>
            <div>请确保网络稳定，建议使用WiFi环境</div>
          </div>
        </div>

        <!-- 用户考试状态提示 -->
        <div v-if="userExamStatus !== 'not_started'" class="status-notice">
          <div class="notice-title">考试状态</div>
          <div class="status-message" :class="getStatusMessageClass()">
            <van-icon :name="getStatusIcon()" />
            <span>{{ getStatusMessage() }}</span>
          </div>
        </div>

        <!-- 开始考试按钮 -->
        <div class="action-buttons">
          <van-button
            type="primary"
            block
            :disabled="!canStartExam()"
            :loading="startLoading"
            @click="startExam"
          >
            {{ getActionButtonText() }}
          </van-button>

          <div v-if="!canStartExam() && !isEnded()" class="countdown-hint">
            距离考试开始还有: {{ formatCountdown() }}
          </div>
        </div>
      </div>
    </template>

    <div v-else class="empty-state">
      <van-empty description="未找到考试信息" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  onUnmounted,
  ref,
} from 'vue';

import {
  showDialog,
  showToast,
} from 'vant';
import {
  useRoute,
  useRouter,
} from 'vue-router';

import { examApi } from '../../api/modules/exam';
import { useExamStore } from '../../stores/exam';

const router = useRouter();
const route = useRoute();
const examStore = useExamStore();

const loading = ref(true);
const startLoading = ref(false);
const examDetail = ref<any>(null);
const countdownTimer = ref<any>(null);
const timeToStart = ref(0);
const userExamStatus = ref<
  "not_started" | "in_progress" | "completed" | "timeout"
>("not_started");

// 获取考试详情
onMounted(async () => {
  const examId = route.params.id as string;
  console.log("ExamDetailView onMounted:", {
    examId,
    routeParams: route.params,
    routePath: route.path,
  });

  if (!examId) {
    showToast("未找到考试ID");
    router.back();
    return;
  }

  try {
    const response = await examStore.fetchExamDetail(examId);
    examDetail.value = response.data;

    // 检查用户的考试记录状态
    try {
      const recordsResponse = await examApi.getExamRecords();
      console.log("用户考试记录:", recordsResponse.data);

      if (
        recordsResponse.data?.data &&
        Array.isArray(recordsResponse.data.data)
      ) {
        const userRecord = recordsResponse.data.data.find(
          (record: any) =>
            record.exam_id?._id === examId || record.exam_id === examId
        );

        if (userRecord) {
          userExamStatus.value = userRecord.status;
          console.log("找到用户考试记录:", userRecord);
        }
      }
    } catch (error) {
      console.error("获取用户考试记录失败:", error);
      // 不影响主流程，继续执行
    }

    // 计算开始时间倒计时
    updateTimeToStart();

    // 设置倒计时更新
    if (!isStarted() && !isEnded()) {
      countdownTimer.value = setInterval(() => {
        updateTimeToStart();
      }, 1000);
    }
  } catch (error) {
    console.error("获取考试详情失败", error);
    showToast("获取考试详情失败");
  } finally {
    loading.value = false;
  }
});

// 组件销毁时清除定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});

// 更新开始时间倒计时
const updateTimeToStart = () => {
  if (!examDetail.value) return;

  const now = new Date().getTime();
  const startTime = new Date(examDetail.value.start_time).getTime();

  if (now < startTime) {
    timeToStart.value = Math.floor((startTime - now) / 1000);
  } else {
    timeToStart.value = 0;
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value);
    }
  }
};

// 格式化倒计时
const formatCountdown = () => {
  const hours = Math.floor(timeToStart.value / 3600);
  const minutes = Math.floor((timeToStart.value % 3600) / 60);
  const seconds = timeToStart.value % 60;

  return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

// 判断是否已开始
const isStarted = () => {
  if (!examDetail.value) return false;

  const now = new Date().getTime();
  const startTime = new Date(examDetail.value.start_time).getTime();

  return now >= startTime;
};

// 判断是否已结束
const isEnded = () => {
  if (!examDetail.value) return false;

  const now = new Date().getTime();
  const endTime = new Date(examDetail.value.end_time).getTime();

  return now > endTime;
};

// 获取考试状态文本
const getStatusText = () => {
  if (!examDetail.value) return "";

  if (isEnded()) {
    return "已结束";
  } else if (isStarted()) {
    return "进行中";
  } else {
    return "即将开始";
  }
};

// 获取状态样式类
const getStatusClass = () => {
  if (!examDetail.value) return "";

  if (isEnded()) {
    return "status-ended";
  } else if (isStarted()) {
    return "status-ongoing";
  } else {
    return "status-upcoming";
  }
};

// 获取用户考试状态样式类
const getStatusMessageClass = () => {
  switch (userExamStatus.value) {
    case "completed":
      return "status-completed";
    case "in_progress":
      return "status-in-progress";
    default:
      return "";
  }
};

// 获取用户考试状态图标
const getStatusIcon = () => {
  switch (userExamStatus.value) {
    case "completed":
      return "check-circle";
    case "in_progress":
      return "clock";
    default:
      return "info";
  }
};

// 获取用户考试状态消息
const getStatusMessage = () => {
  switch (userExamStatus.value) {
    case "completed":
      return "您已完成此考试";
    case "in_progress":
      return "您有一份未完成的考试记录";
    default:
      return "";
  }
};

// 判断是否可以开始考试
const canStartExam = () => {
  if (!examDetail.value) return false;

  // 如果用户已经完成或超时，不能再开始
  if (
    userExamStatus.value === "completed" ||
    userExamStatus.value === "timeout"
  ) {
    return false;
  }

  // 如果用户有正在进行的考试，可以继续
  if (userExamStatus.value === "in_progress") {
    return true;
  }

  // 如果用户还没有开始，且在考试时间内，可以开始
  return isStarted() && !isEnded() && userExamStatus.value === "not_started";
};

// 获取按钮文本
const getActionButtonText = () => {
  if (!examDetail.value) return "开始考试";

  if (userExamStatus.value === "completed") {
    return "考试已完成";
  } else if (userExamStatus.value === "timeout") {
    return "考试已超时";
  } else if (userExamStatus.value === "in_progress") {
    return "继续考试";
  } else if (isEnded()) {
    return "考试已结束";
  } else if (isStarted()) {
    return "开始考试";
  } else {
    return "等待考试开始";
  }
};

// 格式化时间范围
const formatTimeRange = (startTime: string, endTime: string) => {
  const start = new Date(startTime);
  const end = new Date(endTime);

  const formatDate = (date: Date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = String(date.getMinutes()).padStart(2, "0");

    return `${month}月${day}日 ${hour}:${minute}`;
  };

  return `${formatDate(start)} - ${formatDate(end)}`;
};

// 开始考试
const startExam = async () => {
  if (!canStartExam() || !examDetail.value || startLoading.value) return;

  try {
    // 确认开始考试
    await showDialog({
      title: "确认开始考试",
      message: "开始后计时将立即开始，确定现在开始考试吗？",
      confirmButtonText: "开始考试",
      cancelButtonText: "再等等",
    });

    startLoading.value = true;
    await examStore.startExam(examDetail.value._id);
    router.push(`/exam/${examDetail.value._id}`);
  } catch (error) {
    if (error === "cancel") return;
    console.error("开始考试失败", error);
    showToast("开始考试失败");
  } finally {
    startLoading.value = false;
  }
};

// 返回
const onClickLeft = () => {
  router.back();
};
</script>

<style scoped>
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.content-container {
  padding: 16px;
}

.exam-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.exam-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-right: 60px;
}

.exam-status-tag {
  position: absolute;
  top: 16px;
  right: 16px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-ongoing {
  color: #1989fa;
  background-color: rgba(25, 137, 250, 0.1);
}

.status-upcoming {
  color: #ff976a;
  background-color: rgba(255, 151, 106, 0.1);
}

.status-ended {
  color: #969799;
  background-color: rgba(150, 151, 153, 0.1);
}

.exam-info {
  margin-top: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  font-size: 14px;
  color: #646566;
}

.info-item :deep(.van-icon) {
  margin-right: 8px;
  font-size: 16px;
  position: relative;
  top: 2px;
}

.info-item span:nth-child(2) {
  width: 80px;
  color: #969799;
}

.notice-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
}

.status-notice {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.notice-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #323233;
}

.status-message {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 6px;
  font-size: 14px;
}

.status-message :deep(.van-icon) {
  margin-right: 8px;
  font-size: 16px;
}

.status-completed {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #d4edda;
}

.status-in-progress {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.notice-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  font-size: 14px;
  color: #646566;
}

.notice-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #1989fa;
  margin-top: 8px;
  margin-right: 8px;
  flex-shrink: 0;
}

.action-buttons {
  margin-top: 24px;
  margin-bottom: 32px;
}

.countdown-hint {
  text-align: center;
  margin-top: 12px;
  font-size: 14px;
  color: #ff976a;
}
</style>
